package com.huilian.tool.work.weixin.controller;

import com.huilian.tool.common.config.WorkWeiXinConfig;
import com.huilian.tool.common.utils.AesException;
import com.huilian.tool.common.utils.WorkWeiXinUtil;
import com.huilian.tool.redis.ToolRedisKey;
import com.huilian.tool.work.weixin.service.AuthorizeService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.dom4j.DocumentException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.io.Serializable;
import java.io.UnsupportedEncodingException;
import java.util.Date;
import java.util.Map;
import java.util.concurrent.TimeUnit;


/**
 * @Author 少凡
 * @Date 2022-06-09 15:00
 * version 1.0
 */
@Slf4j
@Controller
@RequestMapping("/api/worke-weixin")
public class WorkWeiXinController {
    @Resource
    private WorkWeiXinConfig workWeiXinConfig;
    @Resource
    private AuthorizeService authorizeService;
    @Autowired
    private RedisTemplate<String, Serializable> redisCacheTemplate;


    /**
     * 数据回调URL，指令回调URL验证
     *
     * @param request
     * @return
     */
    @ResponseBody
    @GetMapping("/suite/receive")
    public String receiveSuite1(HttpServletRequest request) throws AesException {
        String result = WorkWeiXinUtil.verifyUrl(request, workWeiXinConfig);
        log.info("GET: /suite/receive: " + result);
        return result;
    }


    /**
     * 数据回调URL
     * 应用配置效验要用到
     *
     * @param request
     * @return
     * @throws AesException
     * @throws IOException
     */
    @ResponseBody
    @GetMapping("/data-callback")
    public String preAuth(HttpServletRequest request) throws AesException {
        String result = WorkWeiXinUtil.verifyUrl(request, workWeiXinConfig);
        log.info("GET: /callback: " + result);
        return result;
    }

    /**
     * 消息事件接口,数据回调URL
     *
     * @param request
     * @return
     * @throws AesException
     * @throws IOException
     * @throws DocumentException
     */
    @ResponseBody
    @PostMapping("/data-callback")
    public String preAuth2(HttpServletRequest request) throws AesException, IOException, DocumentException {
        log.info("POST: /data-callback");
        //这个APPID是企业方授权的APPID，感觉是个坑，因为有时，这里回来的没有那么快,不同的企业，有不同的CorpId
        try {
            String appid = (String) redisCacheTemplate.opsForValue().get("auth_corpid");
            log.info("效验APPID：" + appid);
            if (StringUtils.isNotBlank(appid)) {
                Map<String, String> map = WorkWeiXinUtil.getMapDate(request, workWeiXinConfig, appid);
                log.info(new Date() + "map 是： " + map);
                String infoType = map.get("InfoType");

                log.error("infoType: " + infoType);

                return "success";
            }
        } catch (Exception e) {
            log.error("data-callback效验APPID失败");
        }
        return "success";
    }


    /**
     * 从第三方网站安装应用，获取企业授权。会在回调地址里返回临时授权码
     *
     * @return
     * @throws UnsupportedEncodingException
     */
    @GetMapping("install")
    public String install() {
        String redirectUrl = workWeiXinConfig.getAuthUrl() + "/client/api/worke-weixin/install/redirect";
        String suiteTicket = (String) redisCacheTemplate.opsForValue().get(ToolRedisKey.WORK_WEI_XIN_SUITE_TICKET);
//        Integer authType = 1; //1为测试授权
        Integer authType = 0; //0为正式授权
        return "redirect:" + authorizeService.authInstall(redirectUrl, suiteTicket, authType);
    }


    /**
     * 从第三方网站授权安装成功后的回调，企业授权回调页面
     * 这个只要是获取临时授权码 有效期为10分钟
     *
     * @return
     */
    @ResponseBody
    @GetMapping("install/redirect")
    public String installRedirect(HttpServletRequest request) {
        String authCode = request.getParameter("auth_code");
        String state = request.getParameter("state");
        authorizeService.getPermanentAuthCode((String) redisCacheTemplate.opsForValue().get(ToolRedisKey.WORK_WEI_XIN_SUITE_TICKET), authCode);
        return "跳转到授权成功页！";

    }


    @GetMapping("/login")
    public String authLogin() {
        String redirectUrl = "https://iotbox.huilian.cloud/client/api/worke-weixin/login/redirect";
        String scope = "snsapi_privateinfo";  //snsapi_base静默授权，snsapi_privateinfo 手动授权 snsapi_userinfo
        String state = "state";
        return "redirect:" + authorizeService.authLoginUrl(redirectUrl, scope, state);
    }

    @ResponseBody
    @GetMapping("login/redirect")
    public String loginRedirect(HttpServletRequest request) {
        String authCode = request.getParameter("code");
        String state = request.getParameter("state");
        System.out.println("authCode: " + authCode);
        System.out.println("state: " + state);
        return "跳转到授权成功页！";

    }
}
